package com.rover.controller.system;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.common.SessionInfo;
import com.rover.entity.system.Resource;
import com.rover.service.system.ResourceService;
import com.rover.service.system.RoleResourceService;
import com.rover.service.system.UserService;

/**
 * 菜单资源
 */
@Controller
@RequestMapping("/resourceController")
public class ResourceController {

	@Autowired
	private ResourceService resourceService;

	@Autowired
	private UserService userService;
	@Autowired
	private RoleResourceService roleResourceService;

	@RequestMapping("/getMenu")
	public void caiDan(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		SessionInfo sessionInfo = (SessionInfo) request.getSession()
				.getAttribute("sessionInfo");
		//资源列表
		List<Resource> li = null;
		//此人员对应的角色
		List<Long> liRoles =null;
		//如果是管理员就赛选出父id是0的子资源
		if (sessionInfo.getIsAdmin())
			li = resourceService.selectResource(0l);
		else {
			//获取此用户的所有角色
			 liRoles = userService.getUserRole(sessionInfo.getUser());
			 //获取此用户对应的第一级菜单编号
			 List<Long> liResource= roleResourceService.getFistResourceID(liRoles);
			 //获取此用户对应的第一级菜单
		     li = resourceService.selectResource(liResource);
		}
		String str = getMenuLeaf(li, sessionInfo.getIsAdmin(), liRoles);
		response.setContentType("application/json;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.write(str);
	}

	/*
	 * 返回资源json（这个方法比较消耗资源，原因是每次都要连接数据库判断是否有子节点。
	 * 但这种方法返回的json不会有错，树的结构完全正确）
	 * 
	 * @li 数据源
	 */
	private String getMenu(List<?> li, Boolean isAdmin, List<Long> liRoles) {
		StringBuilder db = new StringBuilder();
		db.append("[");
		for (int i = 0; i < li.size(); i++) {
			Resource menu = (Resource) li.get(i);
			List<Resource> liChildren = null;
			if (isAdmin)
				liChildren = resourceService.selectResource(menu.getId());
			else {
				liChildren = resourceService.selectResource(menu.getId(),
						isAdmin, liRoles);
			}
			String strTemp = "";
			if (liChildren.size() > 0) {
				strTemp = " ,\"leaf\": \"false\" ,\"children\": "
						+ getMenu(liChildren, isAdmin, liRoles);
			} else {
				strTemp = " ,\"leaf\": \"true\" ";
			}
			if ((li.size() - 1) == i) {
				db.append("{ \"text\": \"" + menu.getText() + "\",\"url\":\""
						+ menu.getUrl() + "\",\"iconCls\":\""+menu.getIconCls()+"\",\"id\":\""
						+ menu.getId() + "\"" + strTemp + "}");
			} else {
				db.append("{ \"text\": \"" + menu.getText() + "\",\"url\":\""
						+ menu.getUrl() + "\",\"iconCls\":\""+menu.getIconCls()+"\",\"id\":\""
						+ menu.getId() + "\"" + strTemp + "},");
			}
		}
		db.append(" ]");
		return db.toString();
	}
	/*
	 * 返回资源json  
	 * 这个方法根据left属性判断是否有子节点，效率比较高
	 * （注意：这个方法对left属性有着很高的要求，如果left属性有错误，返回的json树会有问题）
	 * 
	 * @li 数据源
	 */
	private String getMenuLeaf(List<?> li, Boolean isAdmin, List<Long> liRoles) {
		StringBuilder db = new StringBuilder();
		db.append("[");
		for (int i = 0; i < li.size(); i++) {
			Resource menu = (Resource) li.get(i);
			String strTemp = "";
			//判断是否字节点（）
			if (menu.getLeaf()) {
				strTemp = " ,\"leaf\": \"true\" ";
				
			} else {
				List<Resource> liChildren = null;
				if (isAdmin)
					liChildren = resourceService.selectResource(menu.getId());
				else {
					liChildren = resourceService.selectResource(menu.getId(),
							isAdmin, liRoles);
				}
				strTemp = " ,\"leaf\": \"false\" ,\"children\": "
					+ getMenu(liChildren, isAdmin, liRoles);
			}
			if ((li.size() - 1) == i) {
				db.append("{ \"text\": \"" + menu.getText() + "\",\"url\":\""
						+ menu.getUrl() + "\",\"iconCls\":\""+menu.getIconCls()+"\",\"id\":\""
						+ menu.getId() + "\"" + strTemp + "}");
			} else {
				db.append("{ \"text\": \"" + menu.getText() + "\",\"url\":\""
						+ menu.getUrl() + "\",\"iconCls\":\""+menu.getIconCls()+"\",\"id\":\""
						+ menu.getId() + "\"" + strTemp + "},");
			}
		}
		db.append(" ]");
		return db.toString();
	}
	/*
	 * 获取指定角色的资源
	 * */
	@RequestMapping("/getRoleResource")
	public void getRoleResource(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		SessionInfo sessionInfo = (SessionInfo) request.getSession()
				.getAttribute("sessionInfo");
		// 资源列表
		List<Resource> li = null;
		// 此人员对应的角色
		String str = "[]";
		if (request.getParameter("roleId") != null
				&& !request.getParameter("roleId").equals("")) {
			List<Long> liRoles = new ArrayList<Long>();
			// 如果是管理员就赛选出父id是0的子资源
			if (request.getParameter("sAdmin").equals("0")) {
				li = resourceService.selectResource(0l);
			} else {
				liRoles.add(Long.valueOf(request.getParameter("roleId")));
				// 获取此用户对应的第一级菜单编号
				List<Long> liResource = roleResourceService
						.getFistResourceID(liRoles);
				// 获取此用户对应的第一级菜单
				li = resourceService.selectResource(liResource);
			}
			str = getMenuLeaf(li, sessionInfo.getIsAdmin(), liRoles);
			response.setContentType("application/json;charset=UTF-8");
		}
		PrintWriter out = response.getWriter();
		out.write(str);
	}
	/*
	 * 角色资源树的时候使用
	 */
	@RequestMapping("/getAllResource")
	public void getAllResource(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		List<Resource> li = resourceService.selectResource(0l);
		String str = checkedTree(li);
		response.setContentType("application/json;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.write(str);
	}

	/*
	 * 返回带有checkbox的树json
	 * 
	 * @li 数据源
	 */
	private String checkedTree(List<?> li) {
		StringBuilder db = new StringBuilder();
		db.append("[");
		for (int i = 0; i < li.size(); i++) {
			Resource menu = (Resource) li.get(i);
			List<Resource> liChildren = resourceService.selectResource(menu
					.getId());
			String strTemp = "";
			if (liChildren.size() > 0) {
				strTemp = " ,\"leaf\": \"false\" ,\"checked\":false,\"children\": "
						+ checkedTree(liChildren);
			} else {
				strTemp = " ,\"leaf\": \"true\",\"checked\":false ";
			}
			if ((li.size() - 1) == i) {
				db.append("{ \"text\": \"" + menu.getText() + "\",\"url\":\""
						+ menu.getUrl() + "\",\"iconCls\":\""+menu.getIconCls()+"\",\"id\":\""
						+ menu.getId() + "\"" + strTemp + "}");
			} else {
				db.append("{ \"text\": \"" + menu.getText() + "\",\"url\":\""
						+ menu.getUrl() + "\",\"iconCls\":\""+menu.getIconCls()+"\",\"id\":\""
						+ menu.getId() + "\"" + strTemp + "},");
			}
		}
		db.append(" ]");
		return db.toString();
	}
	

}
